// pages/searchDetail/searchDetail.js
import request from '../../util/request'
import PubSub from 'pubsub-js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '', //搜索的关键字
    songList: [], //歌曲列表
    index: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      content: options.content
    })
    this.getSongList(this.data.content)

    PubSub.subscribe('switchTypeSearch', (_, type) => {
      let {
        songList,
        index
      } = this.data
      if (type === 'pre') {
        (index === 0) && (index = songList.length)
        index -= 1;
      } else {
        (index === songList.length - 1) && (index = -1)
        index += 1;
      }
      this.setData({
        index
      })
      let musicId = songList[index].id
      PubSub.publish('musicSearch', musicId)
    })
  },
  async getSongList(content) {
    let songListData = await request('/search', {
      keywords: content
    })
    this.setData({
      songList: songListData.result.songs
    })
  },
  //跳转到歌曲详情页
  toSongDetail(event) {
    let {
      song,
      index
    } = event.currentTarget.dataset
    this.setData({
      index
    })
    wx.navigateTo({
      url: '/songPackage/pages/songDetail/songDetail?musicId=' + song.id
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})